package com.mcxx.modules.tool.service.impl;

import com.mcxx.common.ExternalFileUtil;
import com.mcxx.modules.external.guicai.entity.SHJZT206Y19Entity;
import com.mcxx.modules.external.guicai.entity.SHJZT225Y19Entity;
import com.mcxx.modules.external.guicai.service.read.SHJZ204Y19ReadService;
import com.mcxx.modules.external.guicai.service.write.SHJZT225Y19WriteService;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMemberDTO;
import com.mcxx.modules.miniSalvation.family.entity.BankEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainHistoryEntity;
import com.mcxx.modules.miniSalvation.fundpay.dto.FundPayFamilyDTO;
import com.mcxx.modules.miniSalvation.fundpay.entity.FundPayEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.StandardEntity;
import com.mcxx.modules.miniSalvation.salary.entity.MemberSalaryEntity;
import com.mcxx.modules.statistics.entity.StatisticsExportEntity;
import com.mcxx.modules.system.param.StandardParam;
import com.mcxx.modules.system.service.read.StatisticsExportReadService;
import com.mcxx.modules.system.service.write.StatisticsExportWriteService;
import com.mcxx.modules.temporary.family.dto.TemMemberAndSalaryDTO;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMainHistoryEntity;
import com.mcxx.modules.temporary.family.entity.TmpFamilyMemberHistoryEntity;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMainHistoryReadService;
import com.mcxx.modules.temporary.family.service.read.TmpFamilyMemberHistoryReadService;
import com.mcxx.modules.temporary.fundpay.entity.TmpFundPayEntity;
import com.mcxx.modules.temporary.fundpay.entity.TmpFundPayFamilyEntity;
import com.mcxx.modules.temporary.fundpay.service.read.TmpFundPayFamilyReadService;
import com.mcxx.modules.temporary.order.entity.TmpOrderEntity;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.modules.temporary.salary.service.read.TmpMemberSalaryReadService;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@Service
@TaTransactional
public class GuicaiTempAssService {

    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(GuicaiTempAssService.class);

    @Autowired
    private TmpFundPayFamilyReadService tmpFundPayFamilyReadService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;
    @Autowired
    private TmpFamilyMainHistoryReadService tmpFamilyMainHistoryReadService;
    @Autowired
    private TmpFamilyMemberHistoryReadService tmpFamilyMemberHistoryReadService;
    @Autowired
    private TmpMemberSalaryReadService tmpMemberSalaryReadService;
    @Autowired
    private SHJZT225Y19WriteService shJZT225Y19WriteService;
    @Autowired
    private StatisticsExportReadService statisticsExportReadService;
    @Autowired
    private StatisticsExportWriteService statisticsExportWriteService;
    @Autowired
    private SHJZ204Y19ReadService shjz204Y19ReadService;




    private static String donePath = "E:/gc_temp_done.txt";
    private static String errPath = "E:/gc_error.txt";

    private final RejectedExecutionHandler THREAD_HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();
    private final ThreadPoolExecutor SMS_GATE_SERVE_DELIVER = new ThreadPoolExecutor(20,
            20, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(50),
            THREAD_HANDLER);

    public void findFamilyByPay(String id, String strMonths, String areaCode, List<?> arrs){
        Double standardMoney = 0.0;

        for (Object aa : arrs){
            TmpFundPayEntity fp = (TmpFundPayEntity) aa;
            List<TmpFundPayFamilyEntity> byFundId = tmpFundPayFamilyReadService.getByFundId(fp.getId());
            if(CollectionUtils.isNotEmpty(byFundId)){
                SMS_GATE_SERVE_DELIVER.execute(new executeTempSalvData(byFundId,areaCode,strMonths,id));
            }
        }
    }

    class executeTempSalvData implements Runnable{

        private List<TmpFundPayFamilyEntity> list;

        private String areaCode;

        private String strMonths;

        private String id;

        public executeTempSalvData(List<TmpFundPayFamilyEntity> list,String areaCode,String strMonths,String id){
            this.list = list;
            this.areaCode = areaCode;
            this.strMonths = strMonths;
            this.id = id;
        }

        @Override
        public void run() {
            try {
                if(CollectionUtils.isNotEmpty(list)){
                    for (TmpFundPayFamilyEntity pf : list){
                        if(ExternalFileUtil.traverseFolder(donePath, pf.getOrderId())){
                            logger.info("oId 已处理");
                        }else{

                            if(com.alibaba.druid.util.StringUtils.isEmpty(id)){
                                StatisticsExportEntity en = new StatisticsExportEntity();
                                en.setObjectType("500");
                                en.setYears(strMonths);
                                en.setAreaCode(areaCode);
                                StatisticsExportEntity byYearATypeACode = statisticsExportReadService.getByYearATypeACode(en);
                                if(null == byYearATypeACode){
                                    id = Constant.getUUID();
                                    en.setId(id);
                                    en.setOrgId(areaCode+"000000");
                                    en.setExportTime(new Date());
                                    en.setStatus("0");
                                    statisticsExportWriteService.insertIgnoreNull(en);
                                }else{
                                    if(!"0".equals(byYearATypeACode.getStatus())){
                                        break;
                                    }
                                    id = byYearATypeACode.getId();
                                }
                            }
                            TmpOrderEntity order = tmpOrderReadService.getById(pf.getOrderId());
                            if(null == order){
                                ExternalFileUtil.writeLog(errPath,"未查询到业务记录,orderId:"+pf.getOrderId());
                                continue;
                            }

                            TmpFamilyMainHistoryEntity family = tmpFamilyMainHistoryReadService.getByOrderId(pf.getOrderId());
                            if(null == family){
                                ExternalFileUtil.writeLog(errPath,"未查询到家庭历史记录,orderId:"+pf.getOrderId());
                                continue;
                            }

                            List<TmpFamilyMemberHistoryEntity> memberList = tmpFamilyMemberHistoryReadService.listByOrderId(pf.getOrderId());
                            if(CollectionUtils.isEmpty(memberList)){
                                ExternalFileUtil.writeLog(errPath,"未查询到成员历史记录,orderId:"+pf.getOrderId());
                                continue;
                            }

                            List<TemMemberAndSalaryDTO> memberSalary = tmpMemberSalaryReadService.getMemberListByFamilyId(pf.getOrderId(),pf.getFamilyId());
                            if(CollectionUtils.isEmpty(memberSalary)){
                                ExternalFileUtil.writeLog(errPath,"未查询到成员待遇记录,orderId:"+pf.getOrderId());
                                continue;
                            }
                            TmpFamilyMemberHistoryEntity famOwner = new TmpFamilyMemberHistoryEntity();
                            for(TmpFamilyMemberHistoryEntity mb : memberList){
                                if(mb.getFamilyRelation().equals("01")){
                                    famOwner=mb;
                                }
                            }

                            SHJZT225Y19Entity main = new SHJZT225Y19Entity();
                            main.setRECID(Constant.getUUID());
                            main.setORGUNIT(order.getAreaCode());
                            main.setENTERINGTIME(System.currentTimeMillis()+"");
                            main.setT225_FFJZ_F01_Y19(order.getStartMonth());
                            main.setT225_SFZH_F02_Y19(famOwner.getIdcard().toUpperCase());
                            main.setT225_XM_F03_Y19(famOwner.getName());

                            main.setT225_XB_F04_Y19(famOwner.getSex());
                            main.setT225_MZ_F05_Y19(famOwner.getNation());
                            main.setT225_HJD_F06_Y19(famOwner.getIsLocalPlace().equals("1") ? "1" : "2");

                            if(family.getAddress().length() > 50){
                                main.setT225_ZZ_F07_Y19(family.getAddress().substring(0,50)); // = Server_1.GCServer.Left(this.familyHis.address, 50);
                            }else{
                                main.setT225_ZZ_F07_Y19(family.getAddress());
                            }

                            main.setT225_DH_F09_Y19(family.getPhone());

                            main.setT225_CSRQ_F10_Y19(DateUtils.formatDate(famOwner.getBirthday(),"yyyy-MM-dd"));
                            main.setT225_JZDX_F11_Y19(getPersonType(famOwner.getIdcard(),strMonths));
                            main.setT225_SFWN_F12_Y19("0");
                            main.setT225_JZSY_F13_Y19(convertMainReason(family.getMainReason()));// = this.convertMainReason(this.familyHis.mainReason);
                            Double[] moneys = getMonthMoney(memberSalary);
                            main.setT225_JZJE_F14_Y19(moneys[0]);
                            Integer [] cals = getNums(memberList);
                            main.setT225_XSJZ_F15_Y19(cals[0]);
                            main.setT225_QZWC_F25_Y19(cals[6]);
                            main.setT225_XSJZ_F26_Y19(cals[0]);
                            main.setT225_QZWC_F27_Y19(cals[6]);
                            main.setT225_MRXS_F16_Y19(1);

                            int no = 0;
                            for(TmpFamilyMemberHistoryEntity m : memberList){
                                if(m.getMemberId() != famOwner.getMemberId() &&
                                        m.getIsSaveObject().equals("1")
                                ){
                                    setMemberIdName(main, m, no);
                                    no++;
                                }
                            }
                            main.setSJBHSJ(DateUtils.formatDate(order.getCommitDate(),"yyyy-MM-dd"));
                            main.setSJBHZT("新申请");
                            main.setENTERINGTIME(DateUtil.now());
                            main.setFamily_id(pf.getFamilyId());
                            main.setOrder_id(order.getId());
                            main.setStatisticsId(id);

                            shJZT225Y19WriteService.insertIgnoreNull(main);

                            ExternalFileUtil.writeLog(donePath,pf.getOrderId());
                        }
                    }
                    statisticsExportWriteService.updateStatusById(id,"1");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String convertMainReason(String code){
        if (StringUtils.isEmpty(code)) {
            return "4";
        }
        String[] code1 = {"10", "13", "14", "15", "430422000000001", "430422000000002", "430422000000003", "430422000000004", "430422000000005", "430422000000006", "430422000000007", "430422000000008"};
        String[] code2 = {"12", "430602000000001", "430422000000009"};
        String[] code3 = {"11", "430422000000041", "430422000000042", "430422000000043", "430422000000044", "430422000000045", "430422000000046", "430422000000047", "430422000000048", "430422000000050", "430422000000051", "430423000000001"};

        if (ArrayUtils.contains(code1,code)) {
            return "1";
        }
        else if (ArrayUtils.contains(code2,code)) {
            return "2";
        }
        else if (ArrayUtils.contains(code3,code)) {
            return "3";
        }
        else {
            return "4";
        }
    }

    private Double[] getMonthMoney(List<TemMemberAndSalaryDTO> list){
        Double[] rnt = {0.0, 0.0};
        for (TemMemberAndSalaryDTO m : list) {
            rnt[0] += m.getMemberSalary();
        }
        return rnt;
    }

    private Integer[] getNums(List<TmpFamilyMemberHistoryEntity> list){
        Integer[] rnt = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        for (TmpFamilyMemberHistoryEntity m : list) {
            if (m.getIsSaveObject().equals("1"))
            {
                rnt[0]++;
                if (m.getBirthday() != null) {
                    long bir = m.getBirthday().getTime();
                    long now = System.currentTimeMillis();
                    long chang = 31536000000L;
                    long age = (now - bir) / chang;
                    if (age >= 60)
                        rnt[4]++;
                    else if (age >= 18)
                        rnt[5]++;
                    else
                        rnt[6]++;
                }
                else {
                    rnt[5]++;
                }
                if (m.getSex() != null && m.getSex().equals("2"))
                    rnt[1]++;
            }
        }
        if (rnt[0] == 0)
            rnt[0] = 1;
        return rnt;
    }

    private String getPersonType(String idcard,String sendMonth) {
        String busiTypeByIdcard = shjz204Y19ReadService.getBusiTypeByIdcard(idcard, sendMonth);
        if(Constant.BusinessCode.DIBAO.equals(busiTypeByIdcard)){
            return "1";
        }
        if(Constant.BusinessCode.TEKUN.equals(busiTypeByIdcard)){
            return "2";
        }
        return "3";
    }

    private void setMemberIdName(SHJZT225Y19Entity ent,TmpFamilyMemberHistoryEntity mh,int no){
        if (no == 0) {
            ent.setT225_XSJZ_F17_Y19(mh.getName());
            ent.setT225_SFZH_F18_Y19(mh.getIdcard());
        }
        if (no == 1) {
            ent.setT225_XSJZ_F19_Y19(mh.getName());
            ent.setT225_SFZH_F20_Y19(mh.getIdcard());
        }
        if (no == 2) {
            ent.setT225_XSJZ_F21_Y19(mh.getName());
            ent.setT225_SFZH_F22_Y19(mh.getIdcard());
        }
        if (no == 3) {
            ent.setT225_XSJZ_F23_Y19(mh.getName());
            ent.setT225_SFZH_F24_Y19(mh.getIdcard());
        }
        if (no == 4) {
            ent.setT225_XSJZ_F28_Y19(mh.getName());
            ent.setT225_SFZH_F29_Y19(mh.getIdcard());
        }
        if (no == 5) {
            ent.setT225_XSJZ_F30_Y19(mh.getName());
            ent.setT225_SFZH_F31_Y19(mh.getIdcard());
        }
        if (no == 6) {
            ent.setT225_XSJZ_F32_Y19(mh.getName());
            ent.setT225_SFZH_F33_Y19(mh.getIdcard());
        }
        if (no == 7) {
            ent.setT225_XSJZ_F34_Y19(mh.getName());
            ent.setT225_SFZH_F35_Y19(mh.getIdcard());
        }
        if (no == 8) {
            ent.setT225_XSJZ_F36_Y19(mh.getName());
            ent.setT225_SFZH_F37_Y19(mh.getIdcard());
        }
    }
}
